﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JkUtils
{
    public static class JKStorageFileHelper
    {
            public static readonly string DefaultFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "storage");

            private static string EnsureDirectory(string folderPath)
            {
                if (string.IsNullOrWhiteSpace(folderPath))
                    folderPath = DefaultFolder;

                if (!Directory.Exists(folderPath))
                    Directory.CreateDirectory(folderPath);

                return folderPath;
            }

            private static string GetFileName(string fileName)
            {
                if (!string.IsNullOrWhiteSpace(fileName))
                    return fileName;

                var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                return $"{timestamp}.json";
            }

            public static void SaveToFile(string content, string folderPath = null, string fileName = null)
            {
                var dir = EnsureDirectory(folderPath);
                var fullPath = Path.Combine(dir, GetFileName(fileName));
                File.WriteAllText(fullPath, content, Encoding.UTF8);
            }

            public static async Task SaveToFileAsync(string content, string folderPath = null, string fileName = null)
            {
                var dir = EnsureDirectory(folderPath);
                var fullPath = Path.Combine(dir, GetFileName(fileName));
                using (var writer = new StreamWriter(fullPath, false, Encoding.UTF8))
                {
                    await writer.WriteAsync(content);
                }
            }

            public static async Task<string> LoadFileFromStorage(string fileName)
            {
                var file = Path.Combine(DefaultFolder, fileName);
                return await LoadFromFileAsync(file);
            }

            public static async Task<string> LoadFromFileAsync(string filePath)
            {
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                {
                    return await reader.ReadToEndAsync();
                }
            }

            // 可选：尝试从 JSON 文件中读取为字典
            public static async Task<Dictionary<string, string>> LoadJsonAsDictionaryAsync(string filePath)
            {
                var json = await LoadFromFileAsync(filePath);
                return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
            }
        }
    }